package cp.remote.network;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import cp.remote.config.NetworkConfig;

import android.util.Log;

public class Connection {

	private boolean connected = false;

	public boolean isConnected() {
		return connected;
	}

	private Socket socket = null;
	private BufferedWriter out;
	private BufferedReader in;
	private String ip;
	private int port;

	Connection(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}

	void sendCmd(String cmd) throws IOException {
		if (connected) {
			out.write(cmd);
			out.flush();
		}
	}

	boolean checkCmd() throws IOException{
		if(connected){
			String temp;
			temp = in.readLine();
			if(temp.equals( TaskSwitch.ACK.name() )){
				return true;
			}
			Log.w("Connection", temp);
		}
		return false;
	}
	
	void disconnect() throws IOException {
		if (connected) {
			out.close();
			in.close();
			socket.close();
			Log.d("Connection", "Close Port: " + port);
			connected = false;
		}
	}

	boolean connect() throws UnknownHostException, IOException {
		if (connected == false) {
		    InetSocketAddress adress = new InetSocketAddress(ip, port);
			socket = new Socket();
			socket.connect(adress, NetworkConfig.timeout);
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			out = new BufferedWriter(new OutputStreamWriter(
					socket.getOutputStream()));
			connected = true;
		}
		return connected;
	}
}
